package com.ivan.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserServiceFactory;
import com.ivan.beans.ChatUser;
import com.ivan.util.STRID;

public class InitUserServlet extends HttpServlet {

	private static final long serialVersionUID = -7753479614757097566L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		Set<ChatUser> onlineUsers = null;
		ServletContext context = req.getSession().getServletContext(); 
		Object temp = context.getAttribute(STRID.ONLINE_USERS);
		if(temp != null){
			onlineUsers = (Set<ChatUser>)temp;
		} else {
			onlineUsers = new HashSet<ChatUser>();
		}
		context.setAttribute(STRID.ONLINE_USERS, onlineUsers);
		//Get current logined in user email
		User loginUser = UserServiceFactory.getUserService().getCurrentUser();
		String emailAddr = loginUser.getEmail().trim();
		
		//Send users to client in JSON format
		StringBuffer usersInJSON = new StringBuffer();
		usersInJSON.append("[");
		boolean exists = false;
		for(ChatUser item : onlineUsers){
			exists = true;
			if(!emailAddr.equalsIgnoreCase(item.getEmail())){
				usersInJSON.append("{");
				usersInJSON.append("email: '" + item.getEmail() + "',");
				usersInJSON.append("name: '" + item.getName() + "'");
				usersInJSON.append("},");
			}
		}
		if(exists){
			usersInJSON.deleteCharAt(usersInJSON.length() - 1);
		}
		usersInJSON.append("]");
		resp.setContentType("plain/text;charset=UTF-8");
		PrintWriter writer = resp.getWriter();
		writer.write(usersInJSON.toString());
		writer.flush();
		writer.close();
		System.out.println("JSON User:" + usersInJSON);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		this.doGet(req, resp);
	}
	
}
